//
//  ViewController.m
//  Demo
//
//  Created by shaowei on 5/7/15.
//  Copyright (c) 2015 shaowei. All rights reserved.
//

#import "ViewController.h"
#import "KeyboardShowHideHandler.h"
#import "UIView+Sizes.h"

@interface ViewController ()

@property (nonatomic, strong) KeyboardShowHideHandler *kbHander;

@property (nonatomic, strong) UITextView *textView; //用于测试的view

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //初始化对象
    self.kbHander = [[KeyboardShowHideHandler alloc] init];
    
    //添加测试对象
    self.view.backgroundColor = [UIColor grayColor];
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 80, 260, 150)];
    _textView.height = self.view.height - _textView.top - 20;
    [self.view addSubview:_textView];
    _textView.backgroundColor = [UIColor redColor];
    _textView.text = @"hello, world\n先点击红色区域\n键盘弹出后再点击\"关闭键盘\"\n会发现红色区域跟随键盘 动态的 变化大小 \n这个红色的view只要是UIView及其子类都可以";
    
    //添加关闭键盘的按钮
    UIButton *hideKBBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [hideKBBtn setTitle:@"关闭键盘" forState:UIControlStateNormal];
    [hideKBBtn sizeToFit];
    [hideKBBtn setBackgroundColor:[UIColor blueColor]];
    hideKBBtn.centerX = self.view.width/2;
    hideKBBtn.bottom = _textView.top - 5;
    [hideKBBtn addTarget:self.textView
                  action:@selector(resignFirstResponder)
        forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:hideKBBtn];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//防止收到其他界面的的键盘通知
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidDisappear:YES];
    
    [self.kbHander resetData]; //重置数据+view
    [self addKeyboardHandle]; //重新增加需要跟随键盘变化大小的view
    [self.kbHander startKeyboardNotify];
}

//防止收到其他界面的的键盘通知
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.kbHander stopKeyboardNotify];
}

#pragma mark - Function - Private

- (void)addKeyboardHandle{
    KeyboardHandleWidget *widget = [[KeyboardHandleWidget alloc] init];
    widget.widgetView = self.textView;
    widget.widgetRootView = self.view; //widgetView 所在界面的controller的根view
    widget.frameOfKbHide = self.textView.frame; //widgetView 的原始大小（即键盘未弹出时的大小）
    widget.intervalOfWidgetToKbWhenKbShow = 10; //键盘弹出后，widgetView底部与键盘之间的间隔
    [self.kbHander addWidget:widget];
}

@end
